package io.github.talelin.latticy.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.github.talelin.core.annotation.LoginRequired;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.dto.CreateCommonJobDTO;
import io.github.talelin.latticy.model.CommonJobDO;
import io.github.talelin.latticy.service.CommonJobService;
import io.github.talelin.latticy.vo.CreatedVO;
import io.github.talelin.latticy.vo.DeletedVO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.UpdatedVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Positive;

/**
 * 公域任务表前端控制器
 *
* @author generator@TaleLin
* @since 2020-12-31
*/
@RestController
@RequestMapping("/cms/common-job")
@Validated
public class ICommonJobController {

    @Autowired
    private CommonJobService commonJobService;

    @PostMapping("")
    @LoginRequired
    public CreatedVO create(@RequestBody @Validated CreateCommonJobDTO dto) {
        commonJobService.add(dto);
        return new CreatedVO();
    }

    @PutMapping("/{id}")
    @LoginRequired
    public UpdatedVO update(@PathVariable @Positive(message = "{id.positive}") Long id,
                            @RequestBody @Validated CreateCommonJobDTO dto) {
        commonJobService.edited(id, dto);
        return new UpdatedVO();
    }

    @DeleteMapping("/{id}")
    @LoginRequired
    public DeletedVO delete(@PathVariable @Positive(message = "{id.positive}") Long id) {
        commonJobService.delete(id);
        return new DeletedVO();
    }

    @GetMapping("/{id}")
    @LoginRequired
    public CommonJobDO get(@PathVariable(value = "id") @Positive(message = "{id.positive}") Long id) {
        return commonJobService.getCommonJob(id);
    }

    @GetMapping("/page")
    @LoginRequired
    public PageResponseVO<CommonJobDO> page(
            @RequestParam(name = "count", required = false, defaultValue = "10")
            @Min(value = 1, message = "{page.count.min}")
            @Max(value = 30, message = "{page.count.max}") Long count,
            @RequestParam(name = "page", required = false, defaultValue = "0")
            @Min(value = 0, message = "{page.number.min}") Long page
    ) {
        Page<CommonJobDO> pager = new Page<>(page, count);
        QueryWrapper<CommonJobDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(CommonJobDO::getCreateTime);
        IPage<CommonJobDO> paging = commonJobService.getBaseMapper().selectPage(pager, wrapper);
        return new PageResponseVO<>(paging.getTotal(), paging.getRecords(), paging.getCurrent(), paging.getSize());
    }

}
